<?php


class common extends Weidun_cardModuleSite
{

    function createWxImage($media_id, $dir)
    {
        global $_W, $_GPC;
        load()->classs('weixin.account');

        $account_api = WeAccount::create();
        $access_token = $account_api->getAccessToken();
        $upload_path = ATTACHMENT_ROOT . 'images' . '/' . $this->modulename . '/' . $dir . '/';
        $upload_file_name = time() . "_" . random(6) . '.jpg';
        if (!is_dir($upload_path)) {
            mkdir($upload_path, 0777);
        }
        $targetName = $upload_path . $upload_file_name;
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$media_id}";
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $imageData = curl_exec($curl);
        curl_close($curl);
        $tp = fopen($targetName, "wb");
        fwrite($tp, $imageData);
        fclose($tp);
        if (M('qiniu')->check()) {
            $base64 = 'data:image/jpeg;base64,' . base64_encode(file_get_contents($targetName));
            return $this->createImage($base64);
        }
        return 'images' . '/' . $this->modulename . '/' . $dir . '/' . $upload_file_name;
    }

    function tranTime($time)
    {
        $rtime = date("m-d", $time);
        $htime = date("H:i", $time);
        $time = time() - $time;

        if ($time < 60) {
            $str = '刚刚';
        } elseif ($time < 60 * 60) {
            $min = floor($time / 60);
            $str = $min . '分钟前';
        } elseif ($time < 60 * 60 * 24) {
            $h = floor($time / (60 * 60));
            $str = $h . '小时前';
        } elseif ($time < 60 * 60 * 24 * 3) {
            $d = floor($time / (60 * 60 * 24));
            if ($d == 1)
                $str = '昨天';
            else
                $str = '前天';
        } elseif ($time < 60 * 60 * 24 * 99) {
            $h = floor($time / (60 * 60 * 24));
            $str = $h . '天前';
        } else {
            $str = $rtime;
        }
        return $str;
    }

    public function mc_notice_init($account = 0)
    {
        global $_W;
        if (empty($_W['account'])) {
            if ($account) {
                $_W['account'] = uni_fetch($account);
            } else {
                $_W['account'] = uni_fetch($_W['uniacid']);
            }

        }
        if (empty($_W['account'])) {
            return error(-1, '创建公众号操作类失败');
        }
        $acc = WeAccount::create();
        if (is_null($acc)) {
            return error(-1, '创建公众号操作对象失败');
        }
        return $acc;
    }

    //先插入，异步转码！
    public function createAudioTest($table, $service_id)
    {
        global $_W;
        $acc = $this->mc_notice_init();
        $token = $acc->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" . $token . "&media_id=" . $service_id;
        $key = M('qiniu')->fetch($url, $service_id . ".amr");
        $re_url = $this->createMobileUrl('qiniu2mp3', array('service_id' => $service_id));
        $re_url = str_replace('./', '', $re_url);
        $re_url = $_W['siteroot'] . 'app/' . $re_url;
        $return = M('qiniu')->toMp3($key, $re_url);
        $item = M('' . $table)->getVoiceId($service_id);
        M('' . $table)->update($item);
        return $service_id;
    }

    public function createAudio($table, $id, $service_id = "")
    {
        global $_W;
        $qiniu = M('setting')->getSetting('qiniu');
        $oauth_account = WeAccount::create($_W['account']['oauth']);
        $token = $oauth_account->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" . $token . "&media_id=" . $service_id;
        $key = M('qiniu')->fetch($url, $service_id . ".amr");
        $re_url = $this->createMobileUrl('qiniu2mp3', array('id' => $id, 'table' => $table, 'redirect' => '1'));
        $re_url = str_replace('./', '', $re_url);
        $re_url = $_W['siteroot'] . 'app/' . $re_url;
        $re_url = str_replace('https://', 'http://', $re_url);
        M('qiniu')->toMp3($key, $re_url);
    }

    public function createAudioBack($src)
    {
        global $_W;
        $qiniu = M('setting')->getSetting('qiniu');
        $oauth_account = WeAccount::create($_W['account']['oauth']);
        $token = $oauth_account->getAccessToken();
        $key = M('qiniu')->putFile($src, ATTACHMENT_ROOT . $src);
        return $qiniu['url'] . '/' . $key['key'];
    }

    public function createImage($image)
    {
        load()->func('file');
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $image, $result)) {
            $type = $result[2];
            $name = time() . "_" . random(6) . "." . $type;
            $filename = "images/weidun_alumni/" . date('Y/m/d') . "/" . $name;

            if (file_write($filename, base64_decode(str_replace($result[1], '', $image)))) {
                if (M('qiniu')->check()) {
                    $url = tomedia($filename);
                    $key = M('qiniu')->fetch($url, $filename);
                    if (!empty($key)) {
                        file_delete($filename);
                        return $key;
                    } else {
                        return $filename;
                    }
                } else {
                    $return = $filename;
                }
            }
        } else {
            $return = $image;
        }
        return $return;
    }

    function mc_notice_consume2($openid, $title, $content, $url = '', $thumbs = '')
    {
        global $_W;
        $acc = $this->mc_notice_init();
        $status = 0;
        if (is_error($acc)) {
            return error(-1, $acc['message']);
        }
        if ($_W['account']['level'] == 4) {
            $status = mc_notice_public($openid, $title, $_W['account']['name'], $content);
            if (is_error($status)) {
                $status = $this->mc_notice_custom_news($openid, $title, $content, $url, $thumbs);
            }
        }
        if ($_W['account']['level'] == 3) {
            $status = $this->mc_notice_custom_news($openid, $title, $content, $url, $thumbs);
        }
        return $status;
    }

    function mc_notice_custom_news($openid, $title, $content, $url, $thumb)
    {
        global $_W;
        $acc = $this->mc_notice_init();
        if (is_error($acc)) {
            return error(-1, $acc['message']);
        }
        $fans = pdo_fetch('SELECT salt,acid,openid FROM ' . tablename('mc_mapping_fans') . ' WHERE uniacid = :uniacid AND openid = :openid', array(':uniacid' => $_W['uniacid'], ':openid' => $openid));

        $row = array();
        $row['title'] = urlencode($title);
        $row['description'] = urlencode($content);
        !empty($thumb) && ($row['picurl'] = tomedia($thumb));

        if (strexists($url, 'http://') || strexists($url, 'https://')) {
            $row['url'] = $url;
        } else {
            $pass['time'] = TIMESTAMP;
            $pass['acid'] = $fans['acid'];
            $pass['openid'] = $fans['openid'];
            $pass['hash'] = md5("{$fans['openid']}{$pass['time']}{$fans['salt']}{$_W['config']['setting']['authkey']}");
            $auth = base64_encode(json_encode($pass));
            $vars = array();
            $vars['__auth'] = $auth;
            if (empty($url)) {
                $vars['forward'] = base64_encode($this->createMobileUrl('fans_home'));
            } else {
                $vars['forward'] = base64_encode($url);
            }


            $row['url'] = $_W['siteroot'] . 'app/' . murl('auth/forward', $vars);
        }
        $news[] = $row;
        $send['touser'] = trim($openid);
        $send['msgtype'] = 'news';
        $send['news']['articles'] = $news;
        $status = $acc->sendCustomNotice($send);
        return $status;
    }

    /**
     * 发送模板消息
     * @param $openid
     * @param $school
     * @param $username
     * @param $title
     * @param $content
     * @param $url
     * @return bool
     */
    public function createTplMessage($openid, $school, $username, $title, $content, $url)
    {
        $pro = M('setting')->getSetting('pro');

        $messageTplId = $pro['messageTplId'];
        // 是否代发消息
        if ($pro['subscribeMode'] == 1) {
            $user = M('user')->getInfoByOpenid($openid);
            $openid = $user['agent_openid'];
            load()->classs('weixin.account');
            $acc = WeiXinAccount::create(uni_fetch(21));
        } else {
            $acc = $this->mc_notice_init();
        }

        if ($pro['msgAlerType'] == 1 || $pro['msgAlerType'] == 3) {
            // 学校通知格式
            //{{first.DATA}}
            //学校：{{keyword1.DATA}}
            //通知人：{{keyword2.DATA}}
            //时间：{{keyword3.DATA}}
            //通知内容：{{keyword4.DATA}}
            //{{remark.DATA}}
            $data = array();
            $data['first']['value'] = $title . "\r\n";
            $data['first']['color'] = '#000000';

            $data['keyword1']['value'] = $school . "\r\n";
            $data['keynote1']['color'] = '#173177';

            $data['keyword2']['value'] = $username . "\r\n";
            $data['keynote2']['color'] = '#173177';

            $data['keyword3']['value'] = date('Y年m月d日 H时i分s秒') . "\r\n";
            $data['keyword3']['color'] = '#000000';

            $data['keyword4']['value'] = $content;
            $data['keyword4']['color'] = '#173177';

            $response = $acc->sendTplNotice(trim($openid), trim($messageTplId), $data, $url);

            if (is_error($response)) {
                load()->func('logging');
                logging_run('数据发送失败===原因：' . $response['message'] . '===时间：' . date('Y-m-d H:i') . '===标题：' . $title . '===内容：' . $content);
            }

            return $response;
        }
    }

    /**
     * 格式化开始时间
     * */
    public function format_start_time($created_at)
    {
        if (!is_numeric($created_at)) {
            $created_at = strtotime($created_at);
        }
        $seconds = $created_at - time();
        $minutes = floor($seconds / 60);
        $hours = floor($seconds / (60 * 60));
        $days = floor($seconds / (60 * 60 * 24));
        if ($seconds <= 0) {
            return "报名进行中";
        } else if ($seconds < 60 && $seconds > 0) {
            return "即将开始";
        } elseif ($seconds < 120) {
            return "1分钟后开始";
        } elseif ($minutes < 60) {
            return $minutes . "分钟后开始";
        } elseif ($minutes < 120) {
            return "1小时后开始";
        } elseif ($hours < 24) {
            return $hours . "小时后开始";
        } elseif ($hours < 24 * 2) {
            return "1天后开始";
        } elseif ($days < 30) {
            return $days . "天后开始";
        } elseif ($days < 365) {
            return floor($days / 30) . "个月后开始";
        } else {
            return date("YYYY年mm月dd日", $created_at);
        }
    }

    /**
     * 格式化结束时间
     * */

    public function format_end_time($created_at)
    {
        if (!is_numeric($created_at)) {
            $created_at = strtotime($created_at);
        }

        $seconds = $created_at - time();
        $minutes = floor($seconds / 60);
        $hours = floor($seconds / (60 * 60));
        $days = floor($seconds / (60 * 60 * 24));

        if ($seconds <= 0) {
            return "已经结束";
        } else if ($seconds < 60) {
            return "即将结束";
        } elseif ($seconds < 120) {
            return "1分钟后结束";
        } elseif ($minutes < 60) {
            return $minutes . "分钟后结束";
        } elseif ($minutes < 120) {
            return "1小时后结束";
        } elseif ($hours < 24) {
            return $hours . "小时后结束";
        } elseif ($hours < 24 * 2) {
            return "1天后结束";
        } elseif ($days < 30) {
            return $days . "天后结束";
        } elseif ($days < 365) {
            return floor($days / 30) . "个月后结束";
        } else {
            return floor($days / 365) . "年后截止";
        }
    }

    /**
     * 格式化创建时间
     * */
    public function format_create_time($created_at)
    {
        if (!is_numeric($created_at)) {
            $created_at = strtotime($created_at);
        }
        $seconds = time() - $created_at;
        $minutes = floor($seconds / 60);
        $hours = floor($seconds / (60 * 60));
        $days = floor($seconds / (60 * 60 * 24));
        if ($seconds < 60) {
            return "刚刚";
        } elseif ($seconds < 120) {
            return "1分钟前";
        } elseif ($minutes < 60) {
            return $minutes . "分钟前";
        } elseif ($minutes < 120) {
            return "1小时前";
        } elseif ($hours < 24) {
            return $hours . "小时前";
        } elseif ($hours < 24 * 2) {
            return "1天前";
        } elseif ($days < 30) {
            return $days . "天前";
        } elseif ($days < 365) {
            return floor($days / 30) . "个月前";
        } else {
            return date("YYYY年mm月dd日", $created_at);
        }
    }

    /**
     * 处理敏感词汇
     * @param $str
     * @return mixed
     */
    function filter_word($str)
    {
        global $_W;
        $wordsKey = 'alumni:sensitive_words:'.$_W['uniacid'];
        if (!$wordsCache = cache_read($wordsKey)) {
            $fileName = MODULE_URL.'sensitive_words.txt';
            if (!($words = file_get_contents($fileName))) {
                return $str;
            }
            if ($words) cache_write($wordsKey, $words);
        } else {
            $words = $wordsCache;
        }

        $string = strtolower($str);
        $word = preg_replace("/[1,2,3]\r\n|\r\n/i", '', $words);
        $matched = preg_replace('/' . $word . '/i', '***', $string);
        return $matched;
    }

    /**
     * 处理文本
     * @param string $str
     * @param int $len
     * @return string
     */
    function handle_content($str = '', $len = 200)
    {
        if (mb_strlen($str, 'utf-8') > $len) {
            $content = mb_substr($str, 0, $len, 'utf-8').'...';
        } else {
            $content = $str;
        }
        return $content;
    }

    /**
     * 处理用户数据
     * @param array $members
     * @return array
     */
    function handle_users($members = array())
    {
        if (!empty($members)) {
            foreach ($members as $key => $value) {

                if (empty($value['thumb'])) {
                    $members[$key]['thumb'] = tomedia($this->pro['default_thumb']);
                } else {
                    $members[$key]['thumb'] = tomedia($value['thumb']);
                }

                if ($value['user_type'] == 2) {
                    $members[$key]['truename'] = $members[$key]['truename'].'老师';
                    $members[$key]['classroom'] = '任教开始：'.$value['start_teacher'].'；任教结束：'.$value['end_teacher'];
                } else {
                    $members[$key]['truename'] = $members[$key]['truename'].'校友';
                    switch ($value['learn_type']) {
                        case 1:
                            $members[$key]['classroom'] = '毕业初中：'.$value['grade'].$value['class'];
                            break;
                        case 2:
                            $members[$key]['classroom'] = '毕业高中：'.$value['highgrade'].$value['highclass'];
                            break;
                        case 3:
                            $members[$key]['classroom'] = '毕业初中：'.$value['grade'].$value['class'].'；毕业高中：'.$value['highgrade'].$value['highclass'];
                            break;
                        default:
                            $members[$key]['classroom'] = '毕业初中：'.$value['grade'].$value['class'];
                            break;
                    }
                }

                // 行业
                $industry = M('industry')->getInfo(array('id' => $value['industry']));
                $members[$key]['industryName'] = $industry['name'] ? '行业：'.$industry['name'] : '行业：未知';

                // 是否关注
                $check = M('follow')->check($value['id']);
                $members[$key]['check'] = $check ? 1 : 0;

                // 个人主页
                $members[$key]['url'] = $this->createMobileUrl('tutor', array('userId' => $value['id']));
            }
        }

        return $members;
    }

    /**
     * 处理校友圈
     * @param array $posts
     * @return array
     */
    function handle_post($posts = array())
    {
        if (!empty($posts)) {
            foreach ($posts as $key => $value) {
                // 分类
                $posts[$key]['category'] = M('category')->getInfo($value['category_id']);

                // 谁发布的
                $user =  M('user')->getInfo($value['user_id']);
                $posts[$key]['thumb'] = $user['thumb'] ? tomedia($user['thumb']) : tomedia($this->pro['default_thumb']);

                if ($user['user_type'] == 2) {
                    $posts[$key]['truename'] = $user['truename'].'老师';
                    $posts[$key]['classroom'] = '任教开始：'.$user['start_teacher'].'年；任教结束：'.$user['end_teacher'].'年';
                } else {
                    $posts[$key]['truename'] = $user['truename'].'校友';
                    switch ($value['learn_type']) {
                        case 1:
                            $posts[$key]['classroom'] = '毕业初中：'.$user['grade'].$user['class'];
                            break;
                        case 2:
                            $posts[$key]['classroom'] = '毕业高中：'.$user['highgrade'].$user['highclass'];
                            break;
                        case 3:
                            $posts[$key]['classroom'] = '毕业初中：'.$user['grade'].$user['class'].'；毕业高中：'.$user['highgrade'].$user['highclass'];
                            break;
                        default:
                            $posts[$key]['classroom'] = '毕业初中：'.$user['grade'].$user['class'];
                            break;
                    }
                }

                // 是否点赞
                $praise = M('post_praise')->check($value['id']);
                $posts[$key]['praise'] = $praise ? 1 : 0;


                // 是否收藏
                $receive = M('post_receive')->check($value['id']);
                $posts[$key]['receive'] = $receive ? 1 : 0;


                // 发布时间
                $posts[$key]['time'] = M('common')->tranTime($value['create_time']);

                // 图片
                $images = unserialize($value['images']);
                if (!empty($value['images'])) {
                    foreach ($images as $k => $v) {
                        $images[$k] = tomedia($v);
                    }

                    $posts[$key]['images'] = $images;
                } else {
                    $posts[$key]['images'] = array();
                }

                $posts[$key]['content'] = M('common')->handle_content($value['content']);

                // 详情链接
                $posts[$key]['url'] = $this->createMobileUrl('postDetail', array('post_id' => $value['id']));

                // 评论链接
                $posts[$key]['commentUrl'] = $posts[$key]['url'].'#commentList';
            }
        }
        return $posts;
    }
}